package com.example.demo.service.impl;

import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
import com.example.demo.service.UserService;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserRepository repository;

    @Override
    public Optional<User> add(User req) throws Exception {
        return Optional.of(repository.save(req));
    }

    @Override
    public Optional<User> update(User req) throws Exception {
        return Optional.of(repository.save(req));
    }

    @Override
    public Optional<Boolean> deleteByUserId(String optUserId, String userId) throws Exception {
        Optional<User>  optional = queryByUserId(userId);
        optional.ifPresent(item -> repository.delete(item));
        return Optional.empty();
    }

    @Override
    public Optional<User> queryByUserId(String userId) throws Exception {
        final User req = new User();
        req.setUserId(userId);
        final ExampleMatcher matcher = ExampleMatcher.matchingAll().withMatcher("userId", ExampleMatcher.GenericPropertyMatchers.caseSensitive().exact());
        return repository.findOne(Example.of(req, matcher));
    }

    @Override
    public Optional<List<User>> list(User req) throws Exception {
        return Optional.empty();
    }

    @Override
    public Optional<Page<User>> page(User req) throws Exception {
        return Optional.empty();
    }

    @Override
    public boolean isExist(String loginName, Integer status) throws Exception {
        final User req = new User();
        req.setLoginName(loginName);
        req.setStatus(status);
        final ExampleMatcher matcher = ExampleMatcher.matchingAll()
                .withMatcher("loginName", ExampleMatcher.GenericPropertyMatchers.caseSensitive().exact())
                .withMatcher("status", ExampleMatcher.GenericPropertyMatchers.caseSensitive().exact());
        Optional<User> optional = repository.findOne(Example.of(req, matcher));
        if (optional.isPresent()) {
            return true;
        }
        return false;
    }
}
